package com.vvlive.caibao.smartcity.ui;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AlertDialog.Builder;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.vvlive.caibao.smartcity.app.SmartCityApp;
import com.vvlive.caibao.smartcity.base.BaseActivity;
import com.vvlive.caibao.smartcity.base.GetDeptInfo;
import com.vvlive.caibao.smartcity.base.StringHttpCallBack;
import com.vvlive.caibao.smartcity.bean.AddMeetingBean;
import com.vvlive.caibao.smartcity.bean.MeetingByMonth;
import com.vvlive.caibao.smartcity.bean.NewMeetingInfo;
import com.vvlive.caibao.smartcity.bean.User;
import com.vvlive.caibao.smartcity.callback.LoadDeptRoomCallBack;
import com.vvlive.caibao.smartcity.fragment.PagerAllMeetingsFragment;
import com.vvlive.caibao.smartcity.utils.MeetingsController;
import com.vvlive.caibao.smartcity.utils.TimeUtil;
import com.vvlive.caibao.smartcity.view.CommonActionBar;
import com.vvlive.caibao.smartcity.view.DateTimePickerDialog;

import org.kymjs.kjframe.ui.BindView;

import smartcity.vvlive.caibao.com.smartc.R;

/**
 * Created by zhj on 2015/9/7.
 * 预定会议页面
 */
public class OrderOneMeetingActivity extends BaseActivity {

    public static final int ORDER_RESULT_CODE = 1000;

    @BindView(id = R.id.meeting_name)
    private EditText mMeetingName;
    @BindView(id = R.id.meeting_start_time, click = true)
    private TextView mStartTime;
    @BindView(id = R.id.meeting_end_time, click = true)
    private TextView mEndTime;
    @BindView(id = R.id.meeting_pick_dept, click = true)
    private TextView mPickDept;
    @BindView(id = R.id.meeting_pick_room, click = true)
    private TextView mPickRoom;
    @BindView(id = R.id.meetings_submit, click = true)
    private Button mSubmit;

    private String startDate;
    private String startTime;
    private String endDate;
    private String endTime;
    private String deptId;
    private String roomid;

    private long startMillis;
    private long endMillis;

    private boolean isStartTimeSet = false;
    private boolean isEndTimeSet = false;
    private boolean isDeptPicked = false;
    private boolean isRoomPicked = false;

    private MeetingsController controller;

    private NewMeetingInfo mNewInfo;

    private GetDeptInfo mGetInfo;
    private LoadDeptRoomCallBack loadDeptRoomCallBack;

    @Override
    protected int getContentViewRes() {
        return R.layout.activity_order_one_meeting;
    }

    @Override
    public void initWidget() {
        CommonActionBar actionBar = getCommonActionBar();
        actionBar.setTitle("新建预定");
        actionBar.setMoreVisible(false);
        controller = new MeetingsController();
        mNewInfo = (NewMeetingInfo) getIntent()
                                            .getSerializableExtra(PagerAllMeetingsFragment.NEW_MEETING_INFO_KEY);

        startMillis = System.currentTimeMillis();
        endMillis = getEndTimeMillis(startMillis);  // 30 minutes later than start time;

        if (mNewInfo != null) {
            long starttime = mNewInfo.getStartTime();
            if (starttime > -1) {
                startMillis = starttime;
                startDate = TimeUtil.getTargetDate(starttime, TimeUtil.DATE_FORMAT);
                startTime = TimeUtil.getTargetDate(starttime, TimeUtil.TIME_FORMAT);
                mStartTime.setText(TimeUtil.getTargetDateTime(starttime));
                isStartTimeSet = true;

                endMillis = getEndTimeMillis(startMillis);
                endDate = TimeUtil.getTargetDate(endMillis, TimeUtil.DATE_FORMAT);
                endTime = TimeUtil.getTargetDate(endMillis, TimeUtil.TIME_FORMAT);
                mEndTime.setText(TimeUtil.getTargetDateTime(endMillis));
                isEndTimeSet = true;
            }
            String[] tempDept = mNewInfo.getDept();
            if (tempDept != null) {
                mPickDept.setText(tempDept[1]);
                deptId = tempDept[0];
                isDeptPicked = true;
            }
            String[] tempRoom = mNewInfo.getRoom();
            if (tempRoom != null) {
                mPickRoom.setText(tempRoom[1]);
                roomid = tempRoom[0];
                isRoomPicked = true;
            }
        }

        mGetInfo = new GetDeptInfo();
        loadDeptRoomCallBack = new LoadDeptRoomCallBack();
        loadDeptRoomCallBack.setListener(new LoadDeptRoomCallBack.OnLoadListener() {
            @Override
            public void onLoadFinish() {
                deptNames = loadDeptRoomCallBack.getDeptNames();
                deptIds = loadDeptRoomCallBack.getDeptIds();

                deptId = deptIds[0];

                roomNames = loadDeptRoomCallBack.getRoomBamesByDeptId(deptIds[0]);
                roomIds = loadDeptRoomCallBack.getRoomIdsByDeptId(deptId);
            }

            @Override
            public void onLoadFailed(int code, String msg) {

            }
        });
        mGetInfo.load(loadDeptRoomCallBack);
    }

    /**
     * Get end time by start time, which is 30 minutes later
     * than start time
     *
     * @param startTime
     * @return
     */
    private long getEndTimeMillis(long startTime) {
        return startTime + 1000 * 60 * 30;
    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        int id = v.getId();
        switch (id) {
            case R.id.meeting_start_time:
                setStartTime();
                break;

            case R.id.meeting_end_time:
                setEndTime();
                break;

            case R.id.meeting_pick_dept:
                pickDept();
                break;
            case R.id.meeting_pick_room:
                pickRoom();
                break;
            case R.id.meetings_submit:
                if (canSubmit()) {
                    submit();
                } else {
                    alert("请将会议信息填写完整");
                }
                break;
        }
    }

    private String[] deptNames;
    private String[] deptIds;

    private void pickDept() {
        buildItemsDialog("请选择部门", deptNames, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mPickDept.setText(deptNames[which]);
                deptId = deptIds[which];

                roomNames = loadDeptRoomCallBack.getRoomBamesByDeptId(deptId);
                roomIds = loadDeptRoomCallBack.getRoomIdsByDeptId(deptId);
                roomid = roomIds[0];
                mPickRoom.setText(roomNames[0]);

                isDeptPicked = true;
            }
        });
    }

    /**
     * 设置会议开始时间
     */
    private void setStartTime() {
        DateTimePickerDialog dialog = new DateTimePickerDialog(this, startMillis);
        dialog.setOnDateTimeSetListener(new DateTimePickerDialog.OnDateTimeSetListener() {
            @Override
            public void OnDateTimeSet(android.app.AlertDialog dialog, long date) {
                String dateTime = TimeUtil.getTargetDateTime(date);
                mStartTime.setText(dateTime);

                startDate = TimeUtil.getTargetDate(date, TimeUtil.DATE_FORMAT);
                startTime = TimeUtil.getTargetDate(date, TimeUtil.TIME_FORMAT);

                isStartTimeSet = true;

                startMillis = date;

                // 设置完开始时间后，自动更新结束时间的显示，默认是半个小时以后
                endMillis = getEndTimeMillis(startMillis);
                String endDateTimeText = TimeUtil.getTargetDateTime(endMillis);
                mEndTime.setText(endDateTimeText);
                endDate = TimeUtil.getTargetDate(endMillis, TimeUtil.DATE_FORMAT);
                endTime = TimeUtil.getTargetDate(endMillis, TimeUtil.TIME_FORMAT);
                isEndTimeSet = true;
            }

        });
        dialog.show();
    }

    /**
     * 设置会议结束时间
     */
    private void setEndTime() {
        DateTimePickerDialog dialog2 = new DateTimePickerDialog(this, endMillis);
        dialog2.setOnDateTimeSetListener(new DateTimePickerDialog.OnDateTimeSetListener() {
            @Override
            public void OnDateTimeSet(android.app.AlertDialog dialog, long date) {
                String dateTime = TimeUtil.getTargetDateTime(date);
                mEndTime.setText(dateTime);

                endDate = TimeUtil.getTargetDate(date, TimeUtil.DATE_FORMAT);
                endTime = TimeUtil.getTargetDate(date, TimeUtil.TIME_FORMAT);

                isEndTimeSet = true;
            }

        });
        dialog2.show();
    }

    private String[] roomNames;
    private String[] roomIds;

    private void pickRoom() {
        buildItemsDialog("请选择会议室", roomNames, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mPickRoom.setText(roomNames[which]);
                roomid = roomIds[which];
                isRoomPicked = true;
            }
        });
    }

    private AlertDialog buildItemsDialog(String title, String[] items, OnClickListener clickListener) {
        return new Builder(this).setTitle(title).setItems(items, clickListener).show();
    }

    private ProgressDialog mProgress;

    private void submit() {
        if (SmartCityApp.currentUser == null) {
            toast("请先登录");
            return;
        }

        AddMeetingBean bean = new AddMeetingBean();
        User currentUser = SmartCityApp.currentUser;
        bean.setUserid(currentUser.getUsername());
        bean.setPassword(currentUser.getObjectId());
        bean.setMeeting_room_id(roomid);
        bean.setMeeting_roomname(mPickRoom.getText().toString());
        bean.setMeeting_name(mMeetingName.getText().toString());
        bean.setMeeting_time(startDate);
        bean.setMeeting_time2(endDate);
        bean.setStarttime(startTime);
        bean.setEndtime(endTime);

        mProgress = ProgressDialog.show(this, "", "正在创建...");
        if (startMillis > System.currentTimeMillis()) {
            if (endMillis > startMillis) {
                controller.addMeeting(bean, new StringHttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        dealResult(data);
                        mProgress.dismiss();
                    }

                    @Override
                    public void onError(int errNo, String str) {
                        log("errNo: " + errNo + ", str: " + str);
                        toast(str);
                        mProgress.dismiss();
                    }
                });
            } else {
                toast("结束时间不能早于开始时间！");
            }
        } else {
            toast("新预定的会议开始时间不能早于现在！");
        }

    }

    /**
     * 是否符合提交条件
     * （会议主题不为空，开始时间设置，结束时间设置，机构选择，房间选择）
     *
     * @return
     */
    private boolean canSubmit() {
        return !TextUtils.isEmpty(mMeetingName.getText().toString())
                       && isStartTimeSet && isEndTimeSet && isDeptPicked && isRoomPicked;
    }

    private enum StateCode {

        ADD_RESERVE("选择的会议室已被预定，请选择其他会议室"),
        ADD_ERROR("会议添加失败"),
        OPCODE_ERROR("操作码不对"),
        LIMIT_ERROR("超过日期限定"),
        NO_IN_GROUP("非此机构,不能预定"),
        LOGIN_ERROR("用户账号或密码错误"),
        OK("添加会议成功");

        private final String state;

        StateCode(String state) {
            this.state = state;
        }

        public String getState() {
            return this.state;
        }

    }

    public static final String CREATE_FINISH_KEY = "created";

    private void dealResult(String data) {

        StateCode[] states = StateCode.values();

        if ("OK".equals(data)) {
            toast("会议预定成功");
            MeetingByMonth meetingByMonth = new MeetingByMonth();
            meetingByMonth.setTopic(mMeetingName.getText().toString());

            Bundle bundle = new Bundle();
            bundle.putSerializable(CREATE_FINISH_KEY, meetingByMonth);
            Intent intent = new Intent(this, IndexFragmentActivity.class);
            intent.putExtras(bundle);
            setResult(ORDER_RESULT_CODE);
            finish();
        } else {
            toast(data);
            for (StateCode stateCode : states) {
                if (data.equals(stateCode.name())) {
                    toast(stateCode.getState());
                    return;
                }
            }
        }

    }

}
